using System;
using System.Collections.Generic;
using System.Text;
using Ghasam.Business.Domain.Entity;
using NHibernate;
using NHibernate.Expression;

namespace Ghasam.Business.DAO.Impl
{
    public class InvoiceDao : DaoBase<Invoice>, IInvoiceDao
    {
        public int CountInvoicesByExample( Invoice invoice )
        {
            Example example = Example.Create(invoice).ExcludeZeroes()
                                .ExcludeNulls()
                                .EnableLike(MatchMode.Anywhere);

            ICriteria crit = base.Session.CreateCriteria(typeof(Invoice));
            crit.SetProjection(Projections.Count("Id"));
            return crit.Add(example).UniqueResult<int>();
        }

        public IList<Invoice> GetInvoicesByExample(Invoice invoice, int pageSize, int pageNumber, DateTime lastUpdateStartDate, DateTime lastUpdateEndDate)
        {
            Example example = Example.Create(invoice).ExcludeZeroes()
                                .ExcludeNulls()
                                .EnableLike(MatchMode.Anywhere);

            ICriteria criteria = base.Session.CreateCriteria(typeof(Invoice));
            criteria.Add( Expression.Between("LastUpdate", lastUpdateStartDate, lastUpdateEndDate) );

            return criteria.SetMaxResults(pageSize).SetFirstResult(pageSize * pageNumber)
                       .Add(example).List<Invoice>();
        }

        public long GetMaxSerialByFormal(bool isFormal)
        {
            ICriteria criteria = base.Session.CreateCriteria(typeof(Invoice));
            criteria.Add(Expression.Eq("IsFormal", isFormal));
            criteria.SetProjection( Projections.Max("Serial" ) );

            return criteria.UniqueResult<long>();
        }

        public IList<Invoice> SortInvoice(Invoice invoice, int pageSize, int pageNumber, DateTime lastUpdateStartDate, DateTime lastUpdateEndDate,string param, bool asc)
        {
            Order dir = new Order(param, asc);
            Example example = Example.Create(invoice).ExcludeZeroes()
                    .ExcludeNulls()
                    .EnableLike(MatchMode.Anywhere);

            ICriteria criteria = base.Session.CreateCriteria(typeof(Invoice));
            criteria.CreateAlias("Goods", "goods");
            criteria.CreateAlias("Customer", "customer");
            criteria.Add(Expression.Between("LastUpdate", lastUpdateStartDate, lastUpdateEndDate));

            return criteria.SetMaxResults(pageSize).SetFirstResult(pageSize * pageNumber)
                       .Add(example).List<Invoice>();
            criteria.AddOrder(dir);
            return criteria.SetMaxResults(pageSize).SetFirstResult(pageSize * pageNumber)
           .Add(example).List<Invoice>();
        }
    }
}
